/*
 * Copyright 2008-2009 Aying.Net Powered by Fuchun.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.aying.util.image;

import java.awt.Dimension;
import java.io.File;

import magick.ImageInfo;
import magick.MagickImage;
import net.aying.util.DateUtils;
import net.aying.util.StringUtils;


/**
 * {@code ImageProcessor} 接口的默认实现（jmagick）。
 * 
 * @author  Fuchun
 * @version 1.0, 2009-7-2
 */
public class DeafultImageProcessor implements ImageProcessor {
    
    static {
        System.setProperty("jmagick.systemclassloader", "no");
    }

    /**
     * @see net.aying.util.image.ImageProcessor#scaleImages(java.io.File, net.aying.util.image.ImageScaleSetting)
     */
    public ImageScaleInfo scaleImages(File srcImage, ImageScaleSetting scaleSetting)
            throws ImageProcessException {
        if(srcImage.exists()) {
            if(srcImage.isDirectory()) {
                throw new ImageProcessException(srcImage + " 存在，但它不是一个图片文件！");
            }
        } else {
            throw new ImageProcessException("图片文件 " + srcImage + " 不存在！");
        }
        if(scaleSetting == null) {
            scaleSetting = ImageScaleSetting.getDefaultInstance();
            // 未设置缩放设置信息，则保存在当前源图片所在目录下
            String srcImageDir = srcImage.getAbsoluteFile().getParent();
            String fileName = srcImageDir + File.separator + DateUtils.format("yyyyMMddHHmmssSSS");
            scaleSetting.setBigImage(fileName + ImageScaleSetting.BIG_IMAGE_SUFFIX);
            scaleSetting.setMediumImage(fileName + ImageScaleSetting.MEDIUM_IMAGE_SUFFIX);
            scaleSetting.setSmallImage(fileName + ImageScaleSetting.SMALL_IMAGE_SUFFIX);
            scaleSetting.setThumbImage(fileName + ImageScaleSetting.THUMB_IMAGE_SUFFIX);
            scaleSetting.setSquareImage(fileName + ImageScaleSetting.SQUARE_IMAGE_SUFFIX);
        }
        ImageInfo imageInfo = null;
        MagickImage image = null;
        Dimension srcDim = null;
        try {
            imageInfo = new ImageInfo(srcImage.getAbsolutePath());
            imageInfo.setQuality(100);
            image = new MagickImage(imageInfo);
            srcDim = image.getDimension();
            
            if(StringUtils.hasText(scaleSetting.getBigImage())) {
                Dimension bigDim = calculateScale(srcDim, scaleSetting.getBigImageSide());
                MagickImage bigImage = image.scaleImage((int)bigDim.getWidth(), (int)bigDim.getHeight());
                bigImage.setFileName(scaleSetting.getBigImage());
                bigImage.writeImage(imageInfo);
            }
            if(StringUtils.hasText(scaleSetting.getMediumImage())) {
                Dimension mediumDim = calculateScale(srcDim, scaleSetting.getMediumImageSide());
                MagickImage mediumImage = image.scaleImage((int)mediumDim.getWidth(), (int)mediumDim.getHeight());
                mediumImage.setFileName(scaleSetting.getMediumImage());
                mediumImage.writeImage(imageInfo);
            }
            if(StringUtils.hasText(scaleSetting.getSmallImage())) {
                Dimension smallDim = calculateScale(srcDim, scaleSetting.getSmallImageSide());
                MagickImage smallImage = image.scaleImage((int)smallDim.getWidth(), (int)smallDim.getHeight());
                smallImage.setFileName(scaleSetting.getSmallImage());
                smallImage.writeImage(imageInfo);
            }
            if(StringUtils.hasText(scaleSetting.getThumbImage())) {
                Dimension thumbDim = calculateScale(srcDim, scaleSetting.getThumbImageSide());
                MagickImage thumbImage = image.scaleImage((int)thumbDim.getWidth(), (int)thumbDim.getHeight());
                thumbImage.setFileName(scaleSetting.getThumbImage());
                thumbImage.writeImage(imageInfo);
            }
            if(StringUtils.hasText(scaleSetting.getSquareImage())) {
            	Dimension squareDim = calculateScale(srcDim, scaleSetting.getSquareImageSide());
            	MagickImage squareImage = image.scaleImage((int)squareDim.getWidth(), (int)squareDim.getHeight());
            	squareImage.setFileName(scaleSetting.getSquareImage());
            	squareImage.writeImage(imageInfo);
            }
        } catch(Exception ex) {
            
        }
        return null;
    }
    
    private Dimension calculateScale(Dimension dim, int side) {
        double w = dim.getWidth();
        double h = dim.getHeight();
        if(w >= h) { // 横向图片
            if(w <= side) {
                return new Dimension(dim);
            } else {
                h = h * side / w;
                return new Dimension(side, (int)h);
            }
        } else { // 纵向图片
            if(h <= side) {
                return new Dimension(dim);
            } else {
                w = w * side / h;
                return new Dimension((int)w, side);
            }
        }
    }
    
    public static void main(String[] args) throws Exception {
        DeafultImageProcessor processor = new DeafultImageProcessor();
        processor.scaleImages(new File("E:\\163529_fxGF_0.jpg"), null);
    }
}
